package srv

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/auths"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/beans"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/enums/sys_enum"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/ferror"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gorms"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/sqls"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/xids"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/gqlgen/mgr/gmodel"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/model"
	"gorm.io/gorm"
	"time"
)

func DictInit() {
	reportSrv := &DictSrv{}
	err := beans.ProvideBean(reportSrv)
	asserts.Nil(err, err)
}

type DictSrv struct {
	ReportDbSrv *ReportDbSrv `inject:""`

	Db *gorm.DB `inject:""`

	DictSqlSrv *DictSqlSrv `inject:""`

	DictCategorySrv *DictCategorySrv `inject:""`
}

type SqlDict struct {
	Text  string
	Value string
}

func (s *DictSrv) DictListByCategoryId(ctx context.Context, dictCategoryId string) ([]*model.Dict, error) {
	db := gorms.GetDb(ctx, s.Db)
	rs := make([]*model.Dict, 0)
	err := db.Model(&model.Dict{}).Where(&model.Dict{DictionaryCategoryID: dictCategoryId}).Find(&rs).Error
	if err != nil {
		return nil, err
	}
	return rs, nil
}

func (s *DictSrv) DictMapByCategoryId(ctx context.Context, dictionaryCategoryId string) (map[interface{}]string, error) {
	categoryDetail, err := s.DictCategorySrv.GetByCategoryId(ctx, dictionaryCategoryId)
	if err != nil {
		return nil, err
	}
	if categoryDetail == nil {
		return nil, nil
	}
	return s.DictMapByCategory(ctx, *categoryDetail)
}

func (r *DictSrv) DictMapByCategory(ctx context.Context, dictionaryCategory model.DictCategory) (map[interface{}]string, error) {

	if *dictionaryCategory.CategoryType == sys_enum.SysDictType.SQL() {
		return r.DictSqlSrv.DictMapByCategoryId(ctx, dictionaryCategory.DictionaryCategoryID)
	} else {
		//一般字典
		dicts, err := r.DictListByCategoryId(ctx, dictionaryCategory.DictionaryCategoryID)
		if err != nil {
			return nil, err
		}
		m := map[interface{}]string{}
		for i, _ := range dicts {
			m[dicts[i].Value] = *dicts[i].Remarks
		}
		return m, nil
	}

}

// 通过字典分类编号获取字典列表
func (s *DictSrv) DictListByCategoryCode(ctx context.Context, code string) (map[interface{}]string, error) {

	category, err := s.DictCategorySrv.GetByCategoryCode(ctx, code)
	if err != nil {
		return nil, err
	}
	if category == nil {
		return nil, nil
	}
	return s.DictMapByCategory(ctx, *category)

}

// 添加字典
func (s *DictSrv) AddDict(ctx context.Context, dictCategoryId string, name string, value int, remarks *string) error {
	db := gorms.GetDb(ctx, s.Db)
	now := time.Now()
	currentUser := auths.GetUser(ctx)
	category, err := s.DictCategorySrv.GetByCategoryId(ctx, dictCategoryId)
	if err != nil {
		return err
	}
	if category == nil {
		return ferror.New("分类不存在")
	}
	err = db.Create(&model.Dict{
		DictionaryID:         xids.GetXid(ctx),
		DictionaryCategoryID: dictCategoryId,
		CategoryCode:         &category.CategoryCode,
		Name:                 name,
		Value:                value,
		Remarks:              remarks,
		CreatedAt:            now,
		CreatedBy:            &currentUser.UserId,
		UpdatedAt:            &now,
		UpdatedBy:            &currentUser.UserId,
	}).Error
	if err != nil {
		return ferror.Wrap("保存字典异常", err)
	}
	return nil
}

// 修改字典
func (s *DictSrv) EditDict(ctx context.Context, dictionaryID string, name string, value int, remarks *string) error {
	db := gorms.GetDb(ctx, s.Db)
	now := time.Now()
	currentUser := auths.GetUser(ctx)
	dict, err := s.GetByDictionaryId(ctx, dictionaryID)
	if err != nil {
		return err
	}
	if dict == nil {
		return ferror.New("字典不存在")
	}
	dict.Name = name
	dict.Value = value
	dict.Remarks = remarks
	dict.UpdatedAt = &now
	dict.UpdatedBy = &currentUser.UserId
	err = db.Save(dict).Error
	if err != nil {
		return ferror.Wrap("保存字典异常", err)
	}
	return nil
}

func (s *DictSrv) GetByDictionaryId(ctx context.Context, dictionaryId string) (*model.Dict, error) {
	db := gorms.GetDb(ctx, s.Db)
	r := &model.Dict{}
	err := db.Model(&model.Dict{}).Where(&model.Dict{DictionaryID: dictionaryId}).Take(r).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, ferror.Wrap("获取字典异常", err)
	}
	return r, nil
}

func (s *DictSrv) DeleteDict(ctx context.Context, dictionaryId string) error {
	db := gorms.GetDb(ctx, s.Db)
	err := db.Model(&model.Dict{}).Where(&model.Dict{DictionaryID: dictionaryId}).Delete(nil).Error
	if err != nil {
		return ferror.Wrap("删除字典异常", err)
	}
	return nil
}

func (s *DictSrv) Page(ctx context.Context, req gmodel.DictPageReq) ([]*model.Dict, int, error) {
	db := gorms.GetDb(ctx, s.Db)
	queryParam := make(map[string]interface{}, 0)
	if req.Name != nil {
		queryParam["Name"] = req.Name
	}
	if req.DictCategoryID != "" {
		queryParam["DictCategoryID"] = req.DictCategoryID
	}
	if req.OrderColumn != nil && *req.OrderColumn != "" {
		if *req.OrderBy == "descending" {
			queryParam["OrderByDirection"] = "desc"
		} else {
			queryParam["OrderByDirection"] = "asc"
		}
		switch *req.OrderColumn {
		case "Name":
			queryParam["OrderByColumn"] = "name"
		case "Remarks":
			queryParam["OrderByColumn"] = "remarks"
		case "Value":
			queryParam["OrderByColumn"] = "value"
		case "CreatedAt":
			queryParam["OrderByColumn"] = "created_at"
		case "UpdatedAt":
			queryParam["OrderByColumn"] = "updated_at"
		}
	} else {
		queryParam["OrderByColumn"] = "id"
		queryParam["OrderByDirection"] = "desc"
	}
	var c int
	rs := make([]*model.Dict, 0)
	err := sqls.Page(ctx, db, sqls.PageParam{
		ListSql:     &DictPageSql,
		CountSql:    &DictCountSql,
		M:           queryParam,
		CurrentPage: req.CurrentPage,
		PageSize:    req.PageSize,
	}, &c, &rs)
	if err != nil {
		return nil, 0, err
	}
	return rs, c, nil
}
